package com.easylinkin.linkappapi.safe.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.safe.dao.HiddenDangerMapper;
import com.easylinkin.linkappapi.safe.dao.InspectionPlanMapper;
import com.easylinkin.linkappapi.safe.dao.InspectionTaskMapper;
import com.easylinkin.linkappapi.safe.dto.InspectionPlanDTO;
import com.easylinkin.linkappapi.safe.dto.InspectionTaskDTO;
import com.easylinkin.linkappapi.safe.entity.HiddenDanger;
import com.easylinkin.linkappapi.safe.entity.InspectionPlan;
import com.easylinkin.linkappapi.safe.entity.InspectionTask;
import com.easylinkin.linkappapi.safe.service.InspectionPlanService;
import com.easylinkin.linkappapi.safe.service.InspectionTaskService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 自检计划表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class InspectionPlanServiceImpl extends
    ServiceImpl<InspectionPlanMapper, InspectionPlan> implements InspectionPlanService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Autowired
  private HiddenDangerMapper hiddenDangerMapper;
  @Autowired
  private InspectionTaskMapper inspectionTaskMapper;
  @Autowired
  private InspectionTaskService inspectionTaskService;

  /**
   * 增加
   * @param inspectionPlan
   */
  @Override
  public void insert(InspectionPlan inspectionPlan) {
    /**
     * 验证重复
     */
    this.checkExist(inspectionPlan);
    //设置基本属性
    this.setBase(inspectionPlan);
    this.save(inspectionPlan);
  }

  /**
   * 根据id编辑
   * @param inspectionPlan
   */
  @Override
  public void updateOne(InspectionPlan inspectionPlan) {
    /**
     * 验证重复
     */
    this.checkExist(inspectionPlan);
    //设置基本属性
    this.setBase(inspectionPlan);
    this.updateById(inspectionPlan);
  }

  /**
   * 批量删除
   * @param ids
   */
  @Override
  public void delBatch(Set<Integer> ids) {
    ids.forEach(id ->{
      //有没有隐患和检查
      QueryWrapper<InspectionTask> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("plan_id_",id);
      List<InspectionTask> inspectionTasks = inspectionTaskMapper.selectList(queryWrapper);
      List<Integer> taskIds = inspectionTasks.stream().map(i -> i.getId())
          .collect(Collectors.toList());
      if (taskIds.size() > 0){
        QueryWrapper<HiddenDanger> hWrapper = new QueryWrapper<>();
        hWrapper.in("task_id_",taskIds);
        Integer integer = hiddenDangerMapper.selectCount(hWrapper);
        if (integer > 0){
          throw new BusinessException("请先删除任务项下的检查记录");
        }
      }
      //删除任务项
      Map<String,Object> map = new HashMap<>();
      map.put("plan_id_",id);
      inspectionTaskMapper.deleteByMap(map);
      baseMapper.deleteById(id);
    });
  }

  /**
   * @Description: 发布/中止
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void updateStatus(InspectionPlan inspectionPlan) {
    InspectionPlan plan = baseMapper.selectById(inspectionPlan.getId());
    baseMapper.updateById(inspectionPlan);
    if (Integer.valueOf(2).equals(inspectionPlan.getPublishing())){
      //生成任务项
      inspectionTaskService.insertByPlan(plan,true);
    }
  }

  @Override
  public IPage<InspectionPlanDTO> queryListByPage(RequestModel<InspectionPlan> requestModel) {
    Page page = requestModel.getPage();
    InspectionPlan inspectionPlan = requestModel.getCustomQueryParams();
    //项目id 过滤
    inspectionPlan.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    IPage<InspectionPlanDTO> inspectionPlanIPage = baseMapper.queryListByPage(page, inspectionPlan);
    return inspectionPlanIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(InspectionPlan inspectionPlan) {
    QueryWrapper<InspectionPlan> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.eq("name_",inspectionPlan.getName())
        .eq("tenant_id_",linkappUserContextProducer.getNotNullCurrent().getTenantId());
    //编辑的时候存在id
    Optional.ofNullable(inspectionPlan.getId()).ifPresent(id -> queryWrapper.ne("id",inspectionPlan.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该自检计划已存在");
    }
  }

  /**
   * 设置基本属性
   * @param inspectionPlan
   */
  private void setBase(InspectionPlan inspectionPlan) {
    inspectionPlan.setStartTime(DateUtil.beginOfDay(inspectionPlan.getStartTime()));
    inspectionPlan.setEndTime(DateUtil.endOfDay(inspectionPlan.getEndTime()).offset(DateField.MILLISECOND,-999));
    inspectionPlan.setModifyTime(new Date());
    inspectionPlan.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (null == inspectionPlan.getId()){
      inspectionPlan.setStatus(1);
      inspectionPlan.setPublishing(1);
      inspectionPlan.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      inspectionPlan.setCreateTime(new Date());
      inspectionPlan.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }else {
      inspectionPlan.setStatus(1);
      inspectionPlan.setPublishing(1);
    }
  }
}
